package com.disease.chronic.Component;

import com.disease.chronic.Config.HttpSessionConfig;
import com.disease.chronic.Mappers.AlertHistoryMapper;
import com.disease.chronic.Service.AlertService;
import com.disease.chronic.Service.IndicatorService;
import com.disease.chronic.pojo.AlertHistory;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/alert/{id}",configurator = HttpSessionConfig.class)
public class AlertWebSocket {
    String username;


    IndicatorService indicatorService;


    static AlertService alertService;


    @Setter
    static ApplicationContext applicationContext;

    private final static ConcurrentHashMap<String,Session> sessionPoll = new ConcurrentHashMap<>();

    //存放用户当前的异常报警指标名
    private final static HashMap<String,String> error = new HashMap<>();
    @OnOpen
   public void onOpen(Session session, @PathParam("id") String id){
        alertService = applicationContext.getBean(AlertService.class);

            sessionPoll.put(id,session);

        username = id;
    }


    public static void alert(String username,String indicator,String value,Integer state) throws IOException {
        String message = "";
        if(alertService!=null)
            if(state == 1){
                error.put(username,indicator);
                message+= indicator+"指标异常:"+value;
                //有异常数据存入报警历史
                AlertHistory history = new AlertHistory();
                history.setUsername(username);
                history.setTime(new Date(System.currentTimeMillis()));
                history.setValue(value);
                history.setIndicatorName(indicator);
                alertService.insertAlertRecord(history);
            }else{
                if(error.containsKey(username)&&error.get(username).equals(indicator)) {
                    message += indicator + "指标正常:" + value;
                    if(sessionPoll.containsKey(username)){
                        sessionPoll.get(username).getBasicRemote().sendText(message);
                        return;
                    }
                }
            }
        if(sessionPoll.containsKey(username)){
            sessionPoll.get(username).getBasicRemote().sendText(message);
        }
    }
    @OnClose
    public void onClose(){
        sessionPoll.remove(username);
    }
}
